package net.projects.pro1_weather;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class WeatherForecast {

    private static final String API_KEY = "9d2e385cbc8ca9b0b76692b7efdb0f59";
    private static final String API_URL = "https://api.openweathermap.org/data/2.5/forecast?q=city_name&appid=" + API_KEY + "&lang=zh_cn";


    public static List<String> getweather(String city) {

        try {
            URL url = new URL(API_URL.replace("city_name", city));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            System.out.println(url);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            StringBuilder response = new StringBuilder();
            while ((output = br.readLine()) != null) {
                response.append(output);
            }

            conn.disconnect();

            // 使用 Gson 解析 JSON 数据

            // 打印未来七天的天气预报
//            for (int i = 0; i < weatherForecast.size(); i++) {
//                System.out.println("Day " + (i + 1) + ": " + weatherForecast.get(i));
//            }
            return parseWeatherForecast(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> parseWeatherForecast(String jsonResponse) {
        List<String> forecasts = new ArrayList<>();

        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);
        JsonArray list = jsonObject.getAsJsonArray("list");

        LocalDate currentDate = null;
        LocalDateTime noonDateTime = null;
        String noonWeather = null;

        for (JsonElement element : list) {
            JsonObject dayForecast = element.getAsJsonObject();

            // 提取日期和时间
            String dateTimeStr = dayForecast.get("dt_txt").getAsString();
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 如果是新的一天，或者已经到了下一个中午时间
            if (currentDate == null || currentDate.isBefore(dateTime.toLocalDate())) {
                // 保存前一天中午时间的天气信息
                if (currentDate != null && noonDateTime != null && noonWeather != null) {
                    String forecast = noonDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ": " + noonWeather;
                    forecasts.add(forecast);
                }

                // 更新当前日期和重置中午时间数据
                currentDate = dateTime.toLocalDate();
                noonDateTime = null;
                noonWeather = null;
            }

            // 如果是中午时间点
            if (dateTime.toLocalTime().equals(LocalTime.of(12, 0))) {
                noonDateTime = dateTime;
                JsonArray weatherArray = dayForecast.getAsJsonArray("weather");
                JsonObject weather = weatherArray.get(0).getAsJsonObject();
                noonWeather = weather.get("description").getAsString();
            }
        }
        // 添加最后一天中午时间的天气信息
        if (noonDateTime != null && noonWeather != null) {
            String forecast = noonDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ": " + noonWeather;
            forecasts.add(forecast);
        }
        return forecasts;
    }
}
